package com.xiliubit.cloudpicture.controller;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiliubit.cloudpicture.annotation.AuthCheck;
import com.xiliubit.cloudpicture.api.aliyunai.AliYunAiApi;
import com.xiliubit.cloudpicture.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.xiliubit.cloudpicture.api.aliyunai.model.GetOutPaintingTaskResponse;
import com.xiliubit.cloudpicture.api.imagesearch.ImageSearchApiFacade;
import com.xiliubit.cloudpicture.api.imagesearch.model.ImageSearchResult;
import com.xiliubit.cloudpicture.common.BaseResponse;
import com.xiliubit.cloudpicture.common.DeleteRequest;
import com.xiliubit.cloudpicture.common.ResultUtils;
import com.xiliubit.cloudpicture.constant.CacheNameConstant;
import com.xiliubit.cloudpicture.constant.UserConstant;
import com.xiliubit.cloudpicture.exception.BusinessException;
import com.xiliubit.cloudpicture.exception.ErrorCode;
import com.xiliubit.cloudpicture.exception.ThrowUtils;
import com.xiliubit.cloudpicture.manager.CacheManager;
import com.xiliubit.cloudpicture.manager.auth.SpaceUserAuthManager;
import com.xiliubit.cloudpicture.manager.auth.StpKit;
import com.xiliubit.cloudpicture.manager.auth.annotation.SaSpaceCheckPermission;
import com.xiliubit.cloudpicture.manager.auth.modal.SpaceUserPermissionConstant;
import com.xiliubit.cloudpicture.model.dto.picture.*;
import com.xiliubit.cloudpicture.model.entity.Picture;
import com.xiliubit.cloudpicture.model.entity.Space;
import com.xiliubit.cloudpicture.model.entity.User;
import com.xiliubit.cloudpicture.model.enums.PictureReviewStatusEnum;
import com.xiliubit.cloudpicture.model.vo.PictureVO;
import com.xiliubit.cloudpicture.service.PictureService;
import com.xiliubit.cloudpicture.service.SpaceService;
import com.xiliubit.cloudpicture.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.List;

@RestController
@Slf4j
@Tag(name = "图片接口")
@RequestMapping("/picture")
public class PictureController {

    @Resource
    private PictureService pictureService;

    @Resource
    private UserService userService;

    @Resource
    private CacheManager cacheManager;

    @Resource
    private SpaceService spaceService;

    @Resource
    private AliYunAiApi aliYunAiApi;

    @Resource
    private SpaceUserAuthManager spaceUserAuthManager;

    /**
     * 上传图片
     *
     * @param multipartFile        图片文件
     * @param pictureUploadRequest 包含图片id
     * @param request              请求
     */
    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    @Operation(summary = "上传图片")
//    @io.swagger.v3.oas.annotations.parameters.RequestBody(
//            content = @Content(
//                    mediaType = MediaType.MULTIPART_FORM_DATA_VALUE
//            )
//    )
//    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE) 用户和管理员都可以上传
    public BaseResponse<PictureVO> uploadPicture(@RequestPart("file") MultipartFile multipartFile,
                                                 PictureUploadRequest pictureUploadRequest,
                                                 HttpServletRequest request) {
        log.info("上传图片");
        User loginUser = userService.getLoginUser(request);
        PictureVO pictureVO = pictureService.uploadPicture(multipartFile, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 根据id查询图片
     *
     * @param id      图片id
     * @param request 请求
     * @return 图片信息
     */
    @GetMapping("/get")
    @Operation(summary = "根据id获取图片(管理员)")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Picture> getPicture(long id, HttpServletRequest request) {
        log.info("根据id获取图片(管理员)：{}", id);
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        return ResultUtils.success(picture);
    }

    /**
     * 根据id查询图片
     *
     * @param id 图片id
     * @return 脱敏后的图片信息
     */
    @GetMapping("/get/vo")
    @Operation(summary = "根据id获取图片")
    public BaseResponse<PictureVO> getPictureVO(long id, HttpServletRequest request) {
        log.info("根据 id 获取图片VO:{}", id);
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        Picture picture = pictureService.getById(id);
        ThrowUtils.throwIf(picture == null, ErrorCode.NOT_FOUND_ERROR);
        // 空间权限校验
        Long spaceId = picture.getSpaceId();
        User loginUser = userService.getLoginUser(request);
        Space space = null;
        if (spaceId != null) {
//            pictureService.checkPictureAuth(picture, loginUser);
            // 改为sa-token校验
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR);
            space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        }
        //如果是未审核的照片或者已拒绝的图片，则判断用户权限
        if (!picture.getReviewStatus().equals(PictureReviewStatusEnum.PASS.getValue())){
            //其他普通用户，则拒绝,抛出异常
            if (!picture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }
        // 如果是本人上传的递交审核的图片或者是管理员查询，则返回

        // 获取权限列表
        PictureVO pictureVO = pictureService.getPictureVO(picture, request);
        List<String> permissionList = spaceUserAuthManager.getPermissionList(space, loginUser);
        pictureVO.setPermissionList(permissionList);
        return ResultUtils.success(pictureVO);
    }

    /**
     *  分页查询图片（管理员）
     * @param pictureQueryRequest 图片查询参数
     * @param request 请求
     * @return 图片分页列表
     */
    @PostMapping("/list/page")
    @Operation(summary = "获取图片列表(管理员)")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<Picture>> listPictureByPage(@RequestBody PictureQueryRequest pictureQueryRequest,
                                                           HttpServletRequest request) {
        log.info("获取图片列表(管理员):{}", pictureQueryRequest);
        QueryWrapper<Picture> queryWrapper = pictureService.getQueryWrapper(pictureQueryRequest);
        // 查询数据库
        Page<Picture> picturePage = pictureService.page(new Page<>(pictureQueryRequest.getCurrent(),
                pictureQueryRequest.getPageSize()), queryWrapper);
        return ResultUtils.success(picturePage);
    }

    /**
     * 分页查询图片 -- 引入多级缓存
     * @param pictureQueryRequest 图片查询参数
     * @param request 请求
     * @return 图片分页列表
     */
    @PostMapping("/list/page/vo")
    @Operation(summary = "获取图片列表")
    public BaseResponse<Page<PictureVO>> listPictureVOByPage(
            @RequestBody PictureQueryRequest pictureQueryRequest,
            HttpServletRequest request) throws InterruptedException {
        log.info("获取图片列表:{}", pictureQueryRequest);
        int current = pictureQueryRequest.getCurrent();
        int size = pictureQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);

        // 空间权限校验
        Long spaceId = pictureQueryRequest.getSpaceId();
        // 公开图库
        if (spaceId == null) {
            // 普通用户默认只能查看已过审的公开数据
            pictureQueryRequest.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            pictureQueryRequest.setNullSpaceId(true);
        } else {
            // 私有空间
/*            User loginUser = userService.getLoginUser(request);
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            if (!loginUser.getId().equals(space.getUserId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
            }*/
            boolean hasPermission = StpKit.SPACE.hasPermission(SpaceUserPermissionConstant.PICTURE_VIEW);
            ThrowUtils.throwIf(!hasPermission, ErrorCode.NO_AUTH_ERROR);
        }

        // 缓存前缀
        String prefixKey;
        if (pictureQueryRequest.isNullSpaceId()) {
            // 空间图片
            prefixKey = CacheNameConstant.PUBLIC_CACHE_NAME;
        }else {
            // 公共图库图片
            prefixKey = CacheNameConstant.SPACE_CACHE_NAME;
        }

        // 多级缓存
        Page<PictureVO> pictureVOPage = cacheManager.doPageCache(pictureQueryRequest, prefixKey, () -> {
            // 分页查询数据库
            Page<Picture> page = pictureService.page(new Page<>(current, size),
                    pictureService.getQueryWrapper(pictureQueryRequest));
            return pictureService.getPictureVOPage(page, request);
        });

/*        if (pictureQueryRequest.isNullSpaceId()) {
            // 多级缓存
            pictureVOPage = cacheManager.doPageCache(pictureQueryRequest, "listPictureVOByPage", () -> {
                // 分页查询数据库
                Page<Picture> page = pictureService.page(new Page<>(current, size),
                        pictureService.getQueryWrapper(pictureQueryRequest));
                return pictureService.getPictureVOPage(page, request);
            });
        } else {
            // 分页查询数据库
            Page<Picture> page = pictureService.page(new Page<>(current, size),
                    pictureService.getQueryWrapper(pictureQueryRequest));
            pictureVOPage = pictureService.getPictureVOPage(page, request);
        }*/

        // 返回结果
        return ResultUtils.success(pictureVOPage);
    }

    /**
     *  更新图片（管理员）
     * @param pictureUpdateRequest 修改的图片信息
     * @param request 请求
     */
    @PostMapping("/update")
    @Operation(summary = "更新图片(管理员)")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest,
                                             HttpServletRequest request){
        log.info("更新图片：{}", pictureUpdateRequest);
        if (pictureUpdateRequest == null || pictureUpdateRequest.getId() <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 实体类和DTO进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureUpdateRequest, picture);
        picture.setTags(JSONUtil.toJsonStr(pictureUpdateRequest.getTags()));
        // 校验图片
        pictureService.validPicture(picture);
        // 判断图片是否存在
        Picture oldPicture = pictureService.getById(pictureUpdateRequest.getId());
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 补充审核参数
        User loginUser = userService.getLoginUser(request);
        pictureService.fillReviewParams(picture, loginUser);
        // 修改图片
        boolean result = pictureService.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }

    /**
     * 修改图片
     * @param pictureEditRequest 修改的图片数据
     */
    @PostMapping("/edit")
    @Operation(summary = "修改图片")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPicture(@RequestBody PictureEditRequest pictureEditRequest,
                                             HttpServletRequest request){
        log.info("修改图片:{}", pictureEditRequest);
        if (pictureEditRequest == null || pictureEditRequest.getId() <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 实体类和DTO进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        // 校验图片
        pictureService.validPicture(picture);
        // 判断图片是否存在
        Picture oldPicture = pictureService.getById(pictureEditRequest.getId());
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);

        User loginUser = userService.getLoginUser(request);
        // 补充审核参数
        pictureService.fillReviewParams(picture, loginUser);
        // 校验权限, 替换为sa-token校验
//        pictureService.checkPictureAuth(oldPicture, loginUser);
        // 操作数据库
        boolean result = pictureService.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        if (ObjUtil.isNotNull(oldPicture.getSpaceId())){
            // 如果是空间图片，清理缓存
            cacheManager.clearCacheByPrefixWithScan(CacheNameConstant.SPACE_CACHE_NAME);
        }else{
            if (userService.isAdmin(loginUser)){
                cacheManager.clearCacheByPrefixWithScan(CacheNameConstant.PUBLIC_CACHE_NAME);
            }
        }
        return ResultUtils.success(true);
    }

    /**
     *  删除图片
     * @param deleteRequest 包含图片id
     */
    @PostMapping("/delete")
    @Operation(summary = "删除图片")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_DELETE)
    public BaseResponse<Boolean> deletePicture(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request){
        log.info("删除图片:{}", deleteRequest);
        boolean result = pictureService.deletePicture(deleteRequest, request);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return ResultUtils.success(true);
    }


    /**
     *  获取热门标签和分类
     */
    @GetMapping("/tag_category")
    @Operation(summary = "获取热门标签和分类")
    public BaseResponse<PictureTagCategory> listPictureTagCategory() {
        PictureTagCategory pictureTagCategory = new PictureTagCategory();
        List<String> tagList = Arrays.asList("热门", "搞笑", "生活", "高清", "艺术", "校园", "背景", "简历", "创意");
        List<String> categoryList = Arrays.asList("模板", "电商", "表情包", "素材", "海报");
        pictureTagCategory.setTagList(tagList);
        pictureTagCategory.setCategoryList(categoryList);
        return ResultUtils.success(pictureTagCategory);
    }


    /**
     * 审核图片
     * @param reviewRequest 审核信息
     */
    @PostMapping("/review")
    @Operation(summary = "审核图片")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> doPictureReview(@RequestBody PictureReviewRequest reviewRequest, HttpServletRequest request){
        log.info("审核图片:{}", reviewRequest);
        ThrowUtils.throwIf(reviewRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.doPictureReview(reviewRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 上传图片(URL)
     * @param pictureUploadRequest 图片上传封装请求
     */
    @PostMapping("/upload/url")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_UPLOAD)
    @Operation(summary = "上传图片(URL)")
    public BaseResponse<PictureVO> uploadPictureByUrl(@RequestBody PictureUploadRequest pictureUploadRequest, HttpServletRequest request) {
        log.info("上传图片(URL):{}", pictureUploadRequest);
        User loginUser = userService.getLoginUser(request);
        String fileUrl = pictureUploadRequest.getFileUrl();
        PictureVO pictureVO = pictureService.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
        return ResultUtils.success(pictureVO);
    }

    /**
     * 批量上传图片(仅管理员可用)
     */
    @PostMapping("/upload/batch")
    @Operation(summary = "批量上传图片")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Integer> uploadPictureByBatch(
            @RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest,
            HttpServletRequest request) {
        log.info("开始批量上传图片: {}", pictureUploadByBatchRequest);
        User loginUser = userService.getLoginUser(request);
        Integer integer = pictureService.uploadPictureByBatch(pictureUploadByBatchRequest, loginUser);
        return ResultUtils.success(integer);
    }

    /**
     * 以图搜图(URL)
     */
    @PostMapping("/search/picture")
    @Operation(summary = "以图搜图(URL)")
    public BaseResponse<List<ImageSearchResult>> searchPictureByPicture(@RequestBody SearchPictureByPictureRequest searchPictureByPictureRequest) {
        ThrowUtils.throwIf(searchPictureByPictureRequest == null, ErrorCode.PARAMS_ERROR);
        Long pictureId = searchPictureByPictureRequest.getPictureId();
        ThrowUtils.throwIf(pictureId == null || pictureId <= 0, ErrorCode.PARAMS_ERROR);
        Picture oldPicture = pictureService.getById(pictureId);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 休眠1-4秒，避免给百度搜索接口造成压力
        try {
            Thread.sleep(1000 + RandomUtil.randomInt(0,3000));
        } catch (InterruptedException e) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "搜索失败");
        }
        List<ImageSearchResult> resultList = ImageSearchApiFacade.searchImage(oldPicture.getThumbnailUrl());
        return ResultUtils.success(resultList);
    }

    /**
     * 以颜色搜图
     */
    @PostMapping("/search/color")
    @Operation(summary = "以颜色搜图")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_VIEW)
    public BaseResponse<List<PictureVO>> searchPictureByColor(@RequestBody SearchPictureByColorRequest searchPictureByColorRequest,
                                                              HttpServletRequest request) {
        log.info("以颜色搜图:{}", searchPictureByColorRequest);
        ThrowUtils.throwIf(searchPictureByColorRequest == null, ErrorCode.PARAMS_ERROR);
        String picColor = searchPictureByColorRequest.getPicColor();
        Long spaceId = searchPictureByColorRequest.getSpaceId();
        User loginUser = userService.getLoginUser(request);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        ThrowUtils.throwIf(StrUtil.isBlank(picColor) || ObjectUtil.isEmpty(spaceId), ErrorCode.PARAMS_ERROR);
        List<PictureVO> pictureVOList = pictureService.searchPictureByColor(picColor, spaceId, loginUser);
        return ResultUtils.success(pictureVOList);
    }

    /**
     * 批量修改图片
     */
    @PostMapping("/edit/batch")
    @Operation(summary = "批量修改图片")
    @SaSpaceCheckPermission(value = SpaceUserPermissionConstant.PICTURE_EDIT)
    public BaseResponse<Boolean> editPictureByBatch(@RequestBody PictureEditByBatchRequest pictureEditByBatchRequest, HttpServletRequest request) {
        log.info("批量修改图片:{}", pictureEditByBatchRequest);
        ThrowUtils.throwIf(pictureEditByBatchRequest == null, ErrorCode.PARAMS_ERROR);
        User loginUser = userService.getLoginUser(request);
        pictureService.editPictureByBatch(pictureEditByBatchRequest, loginUser);
        return ResultUtils.success(true);
    }

    /**
     * 创建 AI 扩图任务
     */
    @PostMapping("/out_painting/create_task")
    @Operation(summary = "创建 AI 扩图任务")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<CreateOutPaintingTaskResponse> createPictureOutPaintingTask(
            @RequestBody CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest,
            HttpServletRequest request) {
        log.info("创建 AI 扩图任务:{}", createPictureOutPaintingTaskRequest);
        if (createPictureOutPaintingTaskRequest == null || createPictureOutPaintingTaskRequest.getPictureId() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        CreateOutPaintingTaskResponse response = pictureService.createPictureOutPaintingTask(createPictureOutPaintingTaskRequest, loginUser);
        return ResultUtils.success(response);
    }

    /**
     * 查询 AI 扩图任务
     */
    @GetMapping("/out_painting/get_task")
    @Operation(summary = "查询 AI 扩图任务")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<GetOutPaintingTaskResponse> getPictureOutPaintingTask(String taskId) {
        log.info("查询 AI 扩图任务:{}", taskId);
        ThrowUtils.throwIf(StrUtil.isBlank(taskId), ErrorCode.PARAMS_ERROR);
        GetOutPaintingTaskResponse task = aliYunAiApi.getOutPaintingTask(taskId);
        return ResultUtils.success(task);
    }


    /**
     * 上传图片
     *
     * @param multipartFile 图片文件
     * @param request       请求
     */
    @PostMapping(value = "/avatar", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @Operation(summary = "上传头像")
    public BaseResponse<String> uploadAvatar(@RequestPart("file") MultipartFile multipartFile, HttpServletRequest request) {
        log.info("上传头像");
        User loginUser = userService.getLoginUser(request);
        String avatarUrl = pictureService.uploadAvatar(multipartFile, loginUser);
        return ResultUtils.success(avatarUrl);
    }
}
